#include "log.h"
#include "thread_manger.h"

// 线程池工作函数
void *threadpool_worker(void *arg) {
    threadpool_t *pool = (threadpool_t *)arg;
    while (!pool->shutdown) {
        pthread_mutex_lock(&pool->lock);
        while (pool->task_count == 0 && !pool->shutdown) {
            //if task count is 0 wait task
            //阻塞
            pthread_cond_wait(&pool->cond, &pool->lock);   
        }
        if (pool->shutdown) {
            pthread_mutex_unlock(&pool->lock);
            break;
        }
        task_t task = pool->tasks[pool->head];      //take task form task_queue
        pool->head = (pool->head + 1) % QUEUE_SIZE; //new tash head
        pool->task_count--;
        pthread_mutex_unlock(&pool->lock);

        // 处理任务
        //如果task中有任务处理函数，在这调用实现为不同任务实现不同处理函数
        pool->handle_client(task.sock);
        //close(task.sock);
    }
    pthread_exit(NULL);
}

// 创建线程池中的线程
void threadpool_create(threadpool_t *pool) {
    for (int i = 0; i < MAX_THREADS; ++i) {
        pthread_create(&pool->threads[i], NULL, threadpool_worker, pool);
    }
}

// 线程池初始化
void threadpool_init(threadpool_t *pool) {
    pthread_mutex_init(&pool->lock, NULL);
    pthread_cond_init(&pool->cond, NULL);
    pool->task_count = 0;
    pool->shutdown = 0;
    pool->head = 0;
    pool->tail = 0;

    threadpool_create(pool);
}

// 线程池添加任务
void threadpool_add_task(threadpool_t *pool, task_t task) {
    // DBG("add task\n");
    pthread_mutex_lock(&pool->lock);
    while (pool->task_count == QUEUE_SIZE) {
        pthread_cond_wait(&pool->cond, &pool->lock);
    }
    pool->tasks[pool->tail] = task;
    pool->tail = (pool->tail + 1) % QUEUE_SIZE;
    pool->task_count++;
    pthread_cond_signal(&pool->cond);
    pthread_mutex_unlock(&pool->lock);
    // DBG("add task down\n");
}


void threadpool_destroy(threadpool_t *pool) {

}

